import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/file_gql.dart';

/// 异步图片组件，用于解析和显示需要GraphQL查询的图片
class AsyncImageWidget extends StatefulWidget {
  final String imageUrl;
  final double? width;
  final double? height;
  final BoxFit? fit;

  const AsyncImageWidget({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit,
  });

  @override
  State<AsyncImageWidget> createState() => _AsyncImageWidgetState();
}

class _AsyncImageWidgetState extends State<AsyncImageWidget> {
  static final Map<String, String> _urlCache = {};
  static final Map<String, Future<String?>> _loadingCache = {};

  String? _resolvedUrl;
  bool _isLoading = true;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    // 使用addPostFrameCallback确保在widget完全初始化后再加载图片
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadImage();
    });
  }

  Future<void> _loadImage() async {
    try {
      final resolvedUrl = await _getImageUrl(widget.imageUrl);
      if (mounted) {
        setState(() {
          _resolvedUrl = resolvedUrl;
          _isLoading = false;
        });
      }
    } catch (e) {
      print("图片加载失败: $e");
      if (mounted) {
        setState(() {
          _isLoading = false;
          _hasError = true;
        });
      }
    }
  }

  Future<String?> _getImageUrl(String fileAddr) async {
    
    if (fileAddr.isEmpty) {
      print("图片地址为空");
      return null;
    }

    // 检查缓存
    if (_urlCache.containsKey(fileAddr)) {
      return _urlCache[fileAddr]!;
    }

    // 检查是否正在加载
    if (_loadingCache.containsKey(fileAddr)) {
      return _loadingCache[fileAddr]!;
    }

    // 提取bucketName和objectName
    final pathSegments = fileAddr.split(":");
    if (pathSegments.length != 2) {
      print("图片地址格式不正确，直接返回原始地址: $fileAddr");
      return fileAddr; // 如果不是预期格式，直接返回原始地址
    }

    final bucketName = pathSegments[0];
    final objectName = pathSegments[1];

    // 创建加载Future并缓存
    final future = _fetchDownloadUrl(bucketName, objectName);
    _loadingCache[fileAddr] = future;

    try {
      final result = await future;
      // 缓存结果
      if (result != null) {
        _urlCache[fileAddr] = result;
      }
      return result;
    } finally {
      // 加载完成后从loading cache中移除
      _loadingCache.remove(fileAddr);
    }
  }

  Future<String?> _fetchDownloadUrl(String bucketName, String objectName) async {

    try {
      // 检查context是否有效
      if (!context.mounted) {
        print("Context已卸载，无法继续执行");
        return null;
      }
      
      // 尝试获取GraphQL客户端
      GraphQLClient? client;
      try {
        final providerState = GraphQLProvider.of(context);
        client = providerState?.value;
      } catch (e) {
        print("获取GraphQLProvider失败: $e");
      }
      
      if (client == null) {
        print("GraphQL客户端不可用，返回原始地址");
        // 如果无法获取GraphQL客户端，返回原始地址作为fallback
        return "$bucketName:$objectName";
      }

      
      // 执行查询
      final result = await client.query(
        QueryOptions(
          document: gql(FileGQL.fetchFileDownloadUrl),
          variables: {
            'bucketName': bucketName,
            'objectName': objectName,
          },
        ),
      );


      if (result.hasException) {
        print("GraphQL查询异常: ${result.exception.toString()}");
        // 出现异常时，返回原始地址作为fallback
        return "$bucketName:$objectName";
      }

      if (result.data == null) {
        print("GraphQL查询返回空数据");
        // 数据为空时，返回原始地址作为fallback
        return "$bucketName:$objectName";
      }

      // 安全访问嵌套数据
      try {
        final fileData = result.data!['file'];
        if (fileData == null) {
          print("file数据为空");
          return "$bucketName:$objectName";
        }
        
        final getFileDownloadUrlData = fileData['getFileDownloadUrl'];
        if (getFileDownloadUrlData == null) {
          print("getFileDownloadUrl数据为空");
          return "$bucketName:$objectName";
        }
        
        final url = getFileDownloadUrlData['url'] as String?;
        
        if (url == null || url.isEmpty) {
          print("获取到空的下载URL，返回原始地址");
          return "$bucketName:$objectName";
        }
        return url;
      } catch (e) {
        print("解析GraphQL响应失败: $e");
        // 解析失败时，返回原始地址作为fallback
        return "$bucketName:$objectName";
      }
    } catch (e) {
      print("获取下载URL时发生错误: $e");
      // 发生错误时，返回原始地址作为fallback
      return "$bucketName:$objectName";
    }
  }

  @override
  Widget build(BuildContext context) {

    if (_isLoading) {
      return Center(
        child: SizedBox(
          width: widget.width ?? 50,
          height: widget.height ?? 50,
          child: const CircularProgressIndicator(),
        ),
      );
    }

    if (_hasError || _resolvedUrl == null) {
      print("显示错误状态或空图片");
      return Container(
        width: widget.width,
        height: widget.height,
        color: Colors.grey[300],
        child: const Icon(Icons.error),
      );
    }
    
    // 如果解析后的URL和原始URL相同，说明可能解析失败了，直接使用原始URL
    if (_resolvedUrl == widget.imageUrl) {
      print("使用原始URL显示图片: $_resolvedUrl");
      return Image.network(
        _resolvedUrl!,
        width: widget.width,
        height: widget.height,
        fit: widget.fit ?? BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          print("图片加载失败: $error");
          return Container(
            width: widget.width,
            height: widget.height,
            color: Colors.grey[300],
            child: const Icon(Icons.error),
          );
        },
      );
    }

    return Image.network(
      _resolvedUrl!,
      width: widget.width,
      height: widget.height,
      fit: widget.fit ?? BoxFit.cover,
      errorBuilder: (context, error, stackTrace) {
        print("图片加载失败: $error");
        return Container(
          width: widget.width,
          height: widget.height,
          color: Colors.grey[300],
          child: const Icon(Icons.error),
        );
      },
    );
  }
}